<?php

namespace iBrand\Shop\Backend\Service;

use iBrand\Component\Goods\Models\GoodsSpecRelation;
use iBrand\Component\Goods\Models\SpecsValue;
use iBrand\Component\Goods\Repositories\GoodsProductRepository;
use iBrand\Component\Goods\Repositories\SupplierRepository;
use iBrand\Component\Purchase\Models\Purchase;
use iBrand\Component\Purchase\Repositories\PurchaseRepository;
use iBrand\Shop\Backend\Repository\StoreRepository;
use iBrand\Shop\Core\Models\Clerk;
use iBrand\Shop\Core\Repositories\ClerkRepository;
use iBrand\Shop\Core\Repositories\O2oGoodsRepository;
use iBrand\Shop\Core\Service\WarehouseService;
use iBrand\Store\Backend\Repositories\BrandRepository;
use iBrand\Store\Backend\Repositories\CategoryRepository;
use iBrand\Store\Backend\Model\Spec;
use Illuminate\Support\Facades\DB;
use iBrand\Component\Goods\Models\GoodsProduct;

class CommonService
{
    protected $brandRepository;
    protected $categoryRepository;
    protected $storeRepository;
    protected $supplierRepository;
    protected $clerkRepository;
    protected $purchaseRepository;
    protected $productRepository;
    protected $warehouseService;
    protected $o2oGoodsRepository;

    public function __construct(BrandRepository $brandRepository,
                                CategoryRepository $categoryRepository,
                                StoreRepository $storeRepository,
                                SupplierRepository $supplierRepository,
                                ClerkRepository $clerkRepository,
                                PurchaseRepository $purchaseRepository,
                                GoodsProductRepository $goodsProductRepository,
                                WarehouseService $warehouseService,
                                O2oGoodsRepository $o2oGoodsRepository)
    {
        $this->brandRepository = $brandRepository;
        $this->categoryRepository = $categoryRepository;
        $this->storeRepository = $storeRepository;
        $this->supplierRepository = $supplierRepository;
        $this->clerkRepository = $clerkRepository;
        $this->purchaseRepository = $purchaseRepository;
        $this->productRepository = $goodsProductRepository;
        $this->warehouseService = $warehouseService;
        $this->o2oGoodsRepository = $o2oGoodsRepository;
    }

    public function getYearList()
    {
        $year = date('Y', time());
        $before = $year - env('goods_year_before', 3);
        $result = [];
        for ($i = $before; $i <= $year; $i++) {
            $result[] = ['name' => $i . '上', 'id' => $i . '上'];
            $result[] = ['name' => $i . '下', 'id' => $i . '下'];
        };

        return $result;
    }

    public function getBrandList()
    {
        $brandList = [];
        $brand = $this->brandRepository->findWhere(['is_show' => 1]);
        if ($brand && $brand->count() > 0) {
            $brandList = $brand->toArray();
        }

        return $brandList;
    }

    public function getCategoryList()
    {
        $categories = [];
        $category = $this->categoryRepository->getSortCategory();
        if ($category && $category->count() > 0) {
            $categories = $category->toArray();
        }

        $allCategories = $this->categoryList($categories);

        return ['categories' => $categories, 'allCategories' => $allCategories];
    }

    public function categoryList($categories)
    {
        $result = [];
        $data = collect($categories);
        foreach ($categories as $category) {
            $children = $data->where('parent_id', $category['id']);
            if ($children->count() > 0) {
                $children = $children->values()->toArray();
                $tmp = [];
                foreach ($children as $value) {
                    $tmp[] = ['pTableVO' => $value, 'lstSubHierarchyVO' => []];
                }

                $result[] = ['pTableVO' => $category, 'lstSubHierarchyVO' => $tmp];
            } elseif ($children->count() <= 0 && !$category['parent_id']) {
                $result[] = ['pTableVO' => $category, 'lstSubHierarchyVO' => []];
            }
        }

        return $result;
    }

    public function getSupplierList()
    {
        $suppliers = $this->supplierRepository->findWhere(['status' => 1], ['id', 'name']);
        if ($suppliers && $suppliers->count() > 0) {
            return $suppliers->toArray();
        }

        return [];
    }

    public function getClerkList()
    {
        $clerks = $this->clerkRepository->findWhere(['status' => 1], ['id', 'name']);
        if ($clerks && $clerks->count() > 0) {
            return $clerks->toArray();
        }

        return [];
    }

    public function getSpecList()
    {
        $size = Spec::find(1);
        $sizes = $size->specValue()->where('status', 1)->get()->toArray();

        $color = Spec::find(2);
        $colors = $color->specValue()->where('status', 1)->get()->toArray();

        return ['sizes' => $sizes, 'colors' => $colors];
    }

    public function importStock($shop_id, $goods)
    {
        $clerk = Clerk::where('shop_id', $shop_id)->where('is_clerk_owner', 1)->first();

        $type = 'PURCHASE';
        $remark = '后台导入库存';

        $prefix = 'JT';

        $purchaseData = [
            'shop_id' => $shop_id,
            'code' => $prefix . date('YmdHis') . mt_rand(10000000, 99999999),
            'clerk_id' => $clerk->id,
            'type' => $type,
            'remark' => $remark,
            'status' => Purchase::STATUS_DEFAULT
        ];
        $psku='';
        try {
            DB::beginTransaction();

            $purchase = $this->purchaseRepository->create($purchaseData);

            $quantity = 0;
            $total = 0;
            
           

            foreach ($goods as $good) {
                $good['currentSku']=$good['currentsku'];
                unset($good['currentsku']);

                $product = $this->productRepository->getProductBySku($good['currentSku']);
                $psku=$good['currentSku'];
                if (!$product) {
                    \Log::info($psku . '不存在');
                    continue;
                }

                $item_id = $product->id;
                $item_type = GoodsProduct::class;

                $good['discount'] = 100;
                $good['truePrice'] = $good['price'];
                $good['trueAmount'] = $good['price'] * $good['quantity'];
                $good['goods_id'] = $product->goods_id;

                $goodsInfo = $product->goods;
                $good['discount'] = 100;
                $good['goods_name'] = $goodsInfo->name;
                $good['goods_no'] = $goodsInfo->goods_no;

                $specID = $product->specID;
                $tmpSpec = SpecsValue::find($specID[0]);
                if ($tmpSpec->spec_id == 1) {
                    $size = $tmpSpec;
                    $color = SpecsValue::find($specID[1]);
                } elseif ($tmpSpec->spec_id == 2) {
                    $color = $tmpSpec;
                    $size = SpecsValue::find($specID[1]);
                }
                $colorName = GoodsSpecRelation::where('goods_id', $product->goods_id)->where('spec_value_id', $color->id)->first()->alias;
                $product->colorId = $color->id;
                $product->colorName = $colorName;
                $product->sizeId = $size->id;
                $product->sizeName = $size->name;

                $good['color'] = $colorName;
                $good['color_id'] = $color->id;
                $good['size'] = $size->name;
                $good['size_id'] = $size->id;

                $this->warehouseService->addPurchaseItem($purchase->id, $good, $item_id, $item_type);

                $this->warehouseService->addStockRecord($shop_id, $purchase->id, $good, $type, $item_id, $item_type);

                $o2oGoods = $this->o2oGoodsRepository->findWhere(['status' => 1, 'goods_id' => $good['goods_id'], 'shop_id' => $shop_id])->first();
                if (!$o2oGoods) {
                    $o2oGoods = $this->o2oGoodsRepository->create([
                        'goods_id' => $good['goods_id'],
                        'shop_id' => $shop_id,
                        'price' => $good['price'],
                    ]);
                }

                $o2oGoodsId = $o2oGoods->id;

                $this->warehouseService->addO2oGoodsProduct($shop_id, $o2oGoodsId, $good['goods_id'], $good['quantity'], 'Purchase', $type, $item_id);

                $o2oGoods->restoreStock($good['quantity']);

                $quantity += $good['quantity'];
                $total += $good['quantity'] * $good['price'];
            }

            $purchase->quantity = $quantity;
            $purchase->total = $total;
            $purchase->save();

            DB::commit();
        } catch (\Exception $exception) {
            DB::rollBack();
            \Log::info($psku . $exception->getMessage());
        }
    }
}